<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Login extends FOX_Controller {

    function __construct ()
    {
        parent::__construct();
        $this->load->model('smslog_m');
        $this->config->load('userset');
        $this->load->model('qqUser_m');
        $this->load->model('weibo_m');
		if($this->session->userdata('user_id')){
			redirect(site_url('member'));
		}
    }
	
	public function index()
	{
		$this->load->view('login');
	}

    /**
     * 发送验证码逻辑
     */
    public function ajax_send_sms()
    {
        $mobile =$this->input->get("mobile");

        if(empty($mobile)){
            echo json_encode(['code'=>400,'msg' => '参数缺失']);exit();
        }
        if (!$this->verifyMobile($mobile)) {
            echo json_encode(['code'=>200,'msg' => '号码格式错误']);
            exit;
        }
        // 生成验证码
        $code = $this->creatCodeByRand();
        // 入库
        $data = array(
            'mobile'=>$mobile,
            'yzm'=>$code,
            'type'=>1,
            'createtime'=>date("Y-m-d H:i:s", time()),
        );
        if($this->smslog_m->add_sms_log($data)){
            //发送验证码
            $response = $this->send_sms_code($mobile, $code);
            // 返回
            if (isset($response->Code) && $response->Code == 'OK') {
                // 缓存
                $phoneCode = $this->phoneCodeArr($mobile);
                $phoneCode[$mobile] = ['code'=>$code, 'status'=>0];
                $this->session->set_userdata($mobile.'_info',$phoneCode);
                echo json_encode(['code' => 200, 'msg' => '发送成功']);exit();
            } else {
                echo json_encode(['code' => 400, 'msg' => '发送失败']);exit();
            }
        }else{
            echo json_encode(['code' => 400, 'msg' => '网络异常, 请稍后再试']);exit();
        }

    }

    /**
     * 短信验证码登录
     */
    public function sms_login_in(){
		$url = $this->session->userdata('gourl');
        $mobile =$this->input->post("mobile");
        $yzm =$this->input->post("yzm");
        // 根据mobile查询数据库
        $sms = $this->smslog_m->get_sms_log_by($mobile,$yzm,0);
        if(!empty($sms)){
            // 验证是否正确
            if (!$this->verifyPhoneCode($mobile, $yzm)) {
                echo json_encode(['code'=>400, 'msg'=>"验证码不正确！"]);
                exit;
            }
            // 号码更新为已验证
            $this->smslog_m->sava_sms_log($sms['id'],['is_checked'=>1]);
            // 查看用户是否已注册
            $user = $this->user_m->check_register_username_tel($mobile);
            if(empty($user)){
                // 新用户数据入库
                $salt =get_salt();
                $admin = array(
                    'user_name' => $mobile,
                    'user_password' =>  password_dohash($this->init_pwd($mobile),$salt),
                    'user_salt' => $salt,
                    'user_credit' => $this->config->item('credit_start'),
                    'user_regip' => get_onlineip(),
                    'user_money'=> 0,
                    'user_group'=> 3, // 普通用户
                    'user_regtime' => time(),
                    'user_logtime' => time(),
                    'user_lock'=>0,
                    'user_tel' =>$mobile,
                );
                $this->user_m->register($admin);
                $new_id = $this->db->insert_id();
                $this->user_m->update_user($new_id,array('user_key'=>password_dohash($new_id,$salt)));
                $this->groupAcess_m->insert_user_access(['uid'=>$new_id,'group_id'=>4]);

                $user = $this->user_m->get_user_by_user_id($new_id);
            }
            // 记录登录缓存
            $this->session->set_userdata('user_id',$user['user_id']);
            $loveme = password_dohash($user['user_id'],$user['user_salt']);
            if($loveme){
                $_COOKIE['loveme'] = $loveme;
                setcookie('loveme', $loveme, time() + 86500, '/', '', false, true);
                $this->user_m->update_user($user['user_id'],array('user_key'=>$loveme));
            }
            // 更新登录时间和威望值
            $uid = $this->session->userdata('user_id');
            //更新登陆次数
            $this->user_m->update_ulognum($uid);
            //更新最后登录时间
            $this->user_m->update_user($uid,array('user_logtime'=>time()));
            echo json_encode(['code' => 200, 'msg' => '登陆成功','url'=>$url]);exit();
            exit;
        }else{
            echo json_encode(['code' => 400, 'msg' => '网络异常, 请稍后再试']);exit();
        }

    }
    /**
     * 生成验证码
     * @return string
     */
    private function creatCodeByRand(){
        $token = '';
        $len = 6;
        for ($i = 0; $i < $len; $i++)
            $token .= chr(mt_rand(48, 57));
        return $token;
    }
    /**
     * 短信验证码接口
     * @param $mobile 手机号码
     * @param $code 验证码
     * @param string $temp 短信模板
     * @param string $type 模板自定义变量
     * @return stdClass
     */
    public function send_sms_code($mobile, $code,$temp = 'SMS_132295021',$type = 'code') {

        $this->load->library('alisms');
        $response = $this->alisms->sendSms("销售合伙人平台", $temp, $mobile, [$type => $code]);

        return $response;
//         return (object)['Code'=>"OK"];
    }

    /**
     * 验证手机号规则
     * @param $mobile
     * @return bool
     */
    public function verifyMobile($mobile) {
        $return = false;
        // 正则手机或固定电话
        $isTel = "/^([0-9]{3,4}-)?[0-9]{7,8}$/";
        $isMob = "/^1[3-5,7,8]{1}[0-9]{9}$/";
        if(preg_match($isMob, $mobile) || preg_match($isTel, $mobile)) {
            $return = true;
        }
        return $return;
    }

    /**
     * 查询缓存
     * @param $mobile
     * @return array|mixed
     */
    private function phoneCodeArr($mobile) {
        $info = $this->session->userdata($mobile."_info");
        if (!empty($info)) {
            return $info;
        }
        return [];
    }
    /**
     * 验证 手机验证码
     * @param  Int $mobile    手机号码
     * @param  Int $phoneCode 验证码
     * @return Boolean
     */
    private function verifyPhoneCode($mobile, $phoneCode) {
        $result = false;
        $phoneCodeArr = $this->phoneCodeArr($mobile);
        if (isset($phoneCodeArr[$mobile])) {
            if ($phoneCodeArr[$mobile]['code'] == $phoneCode) {
                $phoneCodeArr[$mobile]['status'] = 1;
                $this->session->set_userdata($mobile.'_info',$phoneCodeArr);
                $result = true;
            }
        }
        return $result;
    }

    /**
     * 初始化用户密码
     * @param $mobile
     */
    private function init_pwd($mobile){

        $str = substr($mobile,6);
//        return md5($str);
        return "123456";
    }

    /*******************************************微信登录********************************************/

    public function wechat_login(){

        if(strstr($_SERVER['HTTP_USER_AGENT'],'MicroMessenger')){
            if($this->session->has_userdata("wechat_user")){
                $con = !empty($this->router->fetch_class()) ? $this->router->fetch_class() : "member"; // 当前控制器
                $func = !empty($this->router->fetch_method()) ? $this->router->fetch_method() : "wechat_login"; // 当前方法名
                if(!in_array($func,["wechatOauthBack","wechatOauthBack2"])){
                    $this->oauth2($con,$func);
                    $openid = $this->session->userdata("wechat_user_info")['id'];
                    // 查看用户是否已注册
                    $wxuser = $this->wxUser_m->get_weixin_users_by_openid($openid);
                    if(empty($wxuser['user_id'])){
                        // 新用户数据入库
                        $salt =get_salt();
                        $admin = array(
                            'user_name' => $wxuser['nickname'],
                            'user_password' =>  password_dohash("123456",$salt),
                            'user_salt' => $salt,
                            'user_credit' => $this->config->item('credit_start'),
                            'user_regip' => get_onlineip(),
                            'user_money'=> 0,
                            'user_group'=> 3, // 普通用户
                            'user_regtime' => time(),
                            'user_logtime' => time(),
                            'user_lock'=>0,
                            'user_avatar'=>$wxuser["headimgurl"],
                        );
                        $this->user_m->register($admin);
                        $new_id = $this->db->insert_id();
                        // 注册送100积分
                        $credit = array(
                            "user_id"=>$new_id,
                            "credit_num"=>$this->config->item('credit_start'),
                            "credit_type"=>0,
                            "credit_time"=>time(),
                        );
                        $this->credit_m->add_fox_credits($credit);
                        $this->user_m->update_user($new_id,array('user_key'=>password_dohash($new_id,$salt)));
                        $this->groupAcess_m->insert_user_access(['uid'=>$new_id,'group_id'=>4]);

                        $user = $this->user_m->get_user_by_user_id($new_id);
                        // 回写user_id
                        $this->wxUser_m->update_weixin_users_by_openid($openid,["user_id"=>$user['user_id']]);
                    }else{
                        $user = $this->user_m->get_user_by_user_id($wxuser['user_id']);
                    }
                    // 记录登录缓存
                    $this->session->set_userdata('user_id',$user['user_id']);
                    $this->session->set_userdata('login_type',"wechat");
                    $loveme = password_dohash($user['user_id'],$user['user_salt']);
                    if($loveme){
                        $_COOKIE['loveme'] = $loveme;
                        setcookie('loveme', $loveme, time() + 86500, '/', '', false, true);
                        $this->user_m->update_user($user['user_id'],array('user_key'=>$loveme));
                    }
                    // 更新登录时间和威望值
                    $uid = $this->session->userdata('user_id');
                    $userinfo=$this->user_m->get_user_by_user_id($uid);
                    $dates = date('Ymd',time());
                    $udates = date('Ymd',$userinfo['user_logtime']);
                    //更新登陆次数
                    $this->user_m->update_ulognum($uid);
                    //更新最后登录时间
                    $this->user_m->update_user($uid,array('user_logtime'=>time()));
                    if($this->config->item('credit_login')>0 && $dates<>$udates){

                        if($this->user_m->update_credit($uid,$this->config->item('credit_login'))){
                            // 登录送2积分
                            $credit = array(
                                "user_id"=>$uid,
                                "credit_num"=>$this->config->item('credit_login'),
                                "credit_type"=>1,
                                "credit_time"=>time(),
                            );
                            $this->credit_m->add_fox_credits($credit);
                        }
                    }
                    redirect('member/index');
                }

            }
        }else{
            exit("请在微信内打开");
        }
    }
    /**
     * 微信登录验证
     * @param  string $action 回调的action
     * @return void
     */
    protected function oauth2($con,$func) {
        // 未登录
        if (!$this->session->has_userdata("wechat_user_info")) {
            $config = [
                'app_id' => config_item("app_id"),
                'oauth' => [
                    'scopes'   => ['snsapi_userinfo'],
                    'callback' => site_url('login/wechatOauthBack2'),
                ],
            ];
            $app = new Application($config);
            $oauth = $app->oauth;
            $this->session->set_userdata('target_url', site_url($con."/".$func));
            $oauth->redirect()->send();
        }
    }
    /**
     * 微信登录验证回调
     * @return void
     */
    public function wechatOauthBack2() {
        $config = [
            'app_id' => config_item("app_id"),
            'secret' => config_item("app_secret"),
        ];
        $app = new Application($config);
        $oauth = $app->oauth;
        // 获取 OAuth 授权结果用户信息
        $user = $oauth->user();
        $userArr = $user->toArray();
        $this->session->set_userdata("wechat_user_info", $userArr);
        $targetUrl = empty($this->session->userdata('target_url')) ? '/' : $this->session->userdata('target_url');
        $wechatUser = $app->user->get($userArr['id']);
//         新增微信表
        if($wechatUser->subscribe == 1){
            $this->wxUser_m->subscribe($wechatUser);
        }else{
            $this->wxUser_m->unsubscribe($userArr);
        }
        redirect($targetUrl);
    }

    /**
     * QQ登录
     * @param string $provider
     */
    public function qq_notice($provider = 'qq')
    {
        $this->config->load('oauth2');
        $allowed_providers = $this->config->item('oauth2');
        if ( ! $provider OR ! isset($allowed_providers[$provider]))
        {
            $this->session->set_flashdata('info', '暂不支持'.$provider.'方式登录.');
            redirect();
            return;
        }
        $this->load->library('oauth2');
        $provider = $this->oauth2->provider($provider, $allowed_providers[$provider]);
        $args = $this->input->get();
        if ($args AND !isset($args['code']))
        {
            $this->session->set_flashdata('info', '授权失败了,可能由于应用设置问题或者用户拒绝授权.<br />具体原因:<br />'.json_encode($args));
            redirect();
            return;
        }
        $code = $this->input->get('code', TRUE);
        if ( ! $code)
        {
            $provider->authorize();
            return;
        }
        else
        {
            try
            {
                $token = $provider->access($code);
                $sns_user = $provider->get_user_info($token);
                if (is_array($sns_user))
                {
                    $this->session->set_userdata('qq_user',$sns_user);
                    $qq_user = $this->qqUser_m->qq_subscribe($sns_user);
                    if(empty($qq_user['user_id'])){
                        // 新用户数据入库
                        $salt =get_salt();
                        $admin = array(
                            'user_name' => $qq_user['nickname'],
                            'user_password' =>  password_dohash("123456",$salt),
                            'user_salt' => $salt,
                            'user_credit' => $this->config->item('credit_start'),
                            'user_regip' => get_onlineip(),
                            'user_money'=> 0,
                            'user_group'=> 4,
                            'user_regtime' => time(),
                            'user_logtime' => time(),
                            'user_lock'=>0,
                            'user_avatar'=>$qq_user["image"],
                        );
                        $this->user_m->register($admin);
                        $new_id = $this->db->insert_id();
                        // 注册送100积分
                        $credit = array(
                            "user_id"=>$new_id,
                            "credit_num"=>$this->config->item('credit_start'),
                            "credit_type"=>0,
                            "credit_time"=>time(),
                        );
                        $this->credit_m->add_fox_credits($credit);
                        $this->user_m->update_user($new_id,array('user_key'=>password_dohash($new_id,$salt)));
                        $this->groupAcess_m->insert_user_access(['uid'=>$new_id,'group_id'=>4]);

                        $user = $this->user_m->get_user_by_user_id($new_id);
                        // 回写user_id
                        $this->qqUser_m->update_qq_users_by_openid($qq_user['openid'],["user_id"=>$user['user_id']]);
                    }else{
                        $user = $this->user_m->get_user_by_user_id($qq_user['user_id']);
                    }
                    // 记录登录缓存
                    $this->session->set_userdata('user_id',$user['user_id']);
                    $this->session->set_userdata('login_type',"qq");
                    $loveme = password_dohash($user['user_id'],$user['user_salt']);
                    if($loveme){
                        $_COOKIE['loveme'] = $loveme;
                        setcookie('loveme', $loveme, time() + 86500, '/', '', false, true);
                        $this->user_m->update_user($user['user_id'],array('user_key'=>$loveme));
                    }
                    // 更新登录时间和威望值
                    $uid = $this->session->userdata('user_id');
                    $userinfo=$this->user_m->get_user_by_user_id($uid);
                    $dates = date('Ymd',time());
                    $udates = date('Ymd',$userinfo['user_logtime']);
                    //更新登陆次数
                    $this->user_m->update_ulognum($uid);
                    //更新最后登录时间
                    $this->user_m->update_user($uid,array('user_logtime'=>time()));
                    if($this->config->item('credit_login')>0 && $dates<>$udates){

                        if($this->user_m->update_credit($uid,$this->config->item('credit_login'))){
                            // 登录送2积分
                            $credit = array(
                                "user_id"=>$uid,
                                "credit_num"=>$this->config->item('credit_login'),
                                "credit_type"=>1,
                                "credit_time"=>time(),
                            );
                            $this->credit_m->add_fox_credits($credit);
                        }
                    }
                    redirect('member/index');
                }
                else
                {
                    $this->session->set_flashdata('info', '获取用户信息失败');
                }
            }
            catch (OAuth2_Exception $e)
            {
                $this->session->set_flashdata('info', '操作失败<pre>'.$e.'</pre>');
            }
        }
        redirect('member/index');
    }

    public function weibo_notice($provider = 'weibo'){
        $this->config->load('oauth2');
        $allowed_providers = $this->config->item('oauth2');
        if ( ! $provider OR ! isset($allowed_providers[$provider]))
        {
            $this->session->set_flashdata('info', '暂不支持'.$provider.'方式登录.');
            redirect();
            return;
        }
        $this->load->library('oauth2');
        $provider = $this->oauth2->provider($provider, $allowed_providers[$provider]);
        $args = $this->input->get();
        if ($args AND !isset($args['code']))
        {
            $this->session->set_flashdata('info', '授权失败了,可能由于应用设置问题或者用户拒绝授权.<br />具体原因:<br />'.json_encode($args));
            redirect();
            return;
        }
        $code = $this->input->get('code', TRUE);
        if ( ! $code)
        {
            $provider->authorize();
            return;
        }
        else
        {
            try
            {
                $token = $provider->access($code);
                $sns_user = $provider->get_user_info($token);
                if (is_array($sns_user))
                {
                    $this->session->set_userdata('weibo_user',$sns_user);
                    $weibo_user = $this->weibo_m->weibo_subscribe($sns_user);
                    if(empty($weibo_user['user_id'])){
                        // 新用户数据入库
                        $salt =get_salt();
                        $admin = array(
                            'user_name' => $weibo_user['nickname'],
                            'user_password' =>  password_dohash("123456",$salt),
                            'user_salt' => $salt,
                            'user_credit' => $this->config->item('credit_start'),
                            'user_regip' => get_onlineip(),
                            'user_money'=> 0,
                            'user_group'=> 4,
                            'user_regtime' => time(),
                            'user_logtime' => time(),
                            'user_lock'=>0,
                            'user_avatar'=>$weibo_user["image"],
                        );
                        $this->user_m->register($admin);
                        $new_id = $this->db->insert_id();
                        // 注册送100积分
                        $credit = array(
                            "user_id"=>$new_id,
                            "credit_num"=>$this->config->item('credit_start'),
                            "credit_type"=>0,
                            "credit_time"=>time(),
                        );
                        $this->credit_m->add_fox_credits($credit);
                        $this->user_m->update_user($new_id,array('user_key'=>password_dohash($new_id,$salt)));
                        $this->groupAcess_m->insert_user_access(['uid'=>$new_id,'group_id'=>4]);

                        $user = $this->user_m->get_user_by_user_id($new_id);
                        // 回写user_id
                        $this->weibo_m->update_weibo_users_by_openid($weibo_user['openid'],["user_id"=>$user['user_id']]);
                    }else{
                        $user = $this->user_m->get_user_by_user_id($weibo_user['user_id']);
                    }
                    // 记录登录缓存
                    $this->session->set_userdata('user_id',$user['user_id']);
                    $this->session->set_userdata('login_type',"qq");
                    $loveme = password_dohash($user['user_id'],$user['user_salt']);
                    if($loveme){
                        $_COOKIE['loveme'] = $loveme;
                        setcookie('loveme', $loveme, time() + 86500, '/', '', false, true);
                        $this->user_m->update_user($user['user_id'],array('user_key'=>$loveme));
                    }
                    // 更新登录时间和威望值
                    $uid = $this->session->userdata('user_id');
                    $userinfo=$this->user_m->get_user_by_user_id($uid);
                    $dates = date('Ymd',time());
                    $udates = date('Ymd',$userinfo['user_logtime']);
                    //更新登陆次数
                    $this->user_m->update_ulognum($uid);
                    //更新最后登录时间
                    $this->user_m->update_user($uid,array('user_logtime'=>time()));
                    if($this->config->item('credit_login')>0 && $dates<>$udates){

                        if($this->user_m->update_credit($uid,$this->config->item('credit_login'))){
                            // 登录送2积分
                            $credit = array(
                                "user_id"=>$uid,
                                "credit_num"=>$this->config->item('credit_login'),
                                "credit_type"=>1,
                                "credit_time"=>time(),
                            );
                            $this->credit_m->add_fox_credits($credit);
                        }
                    }
                    redirect('member/index');
                }
                else
                {
                    $this->session->set_flashdata('info', '获取用户信息失败');
                }
            }
            catch (OAuth2_Exception $e)
            {
                $this->session->set_flashdata('info', '操作失败<pre>'.$e.'</pre>');
            }
        }
        redirect('member/index');
    }

}
